import axios from "axios";
import Cookies from 'js-cookie'
import { Message } from "@arco-design/web-react";
import { KNOWLEDGE_KEY ,API_URL} from '@/config'
export const routes = {
  createDatasets:{
    method: "POST",
    url: () => `/datasets`,
  },
  datasets:{
    method: "GET",
    url: () => `/datasets`,
  },
  documents: {
    method: "GET",
    url: (dataset_id:any) => `/datasets/${dataset_id}/documents`,
  },
  downloadDocument: {
    method: "GET",
    url: (dataset_id:any,document_id:any) => `/datasets/${dataset_id}/documents/${document_id}/upload-file`,
  },
  uploadDocument: {
    method: "POST",
    url: (dataset_id:any) => `/datasets/${dataset_id}/document/create-by-file`,
  },
 
}  

 class TwoDifyClient{

  async sendRequest(
    method:string,
    url:string,
    data:any = undefined,
    params:any = undefined,
    headerParams = {}
  ) {

    const headers = {
      ...{
        Authorization: `Bearer ${KNOWLEDGE_KEY }`,
        "Content-Type": "application/json",
      },
      ...headerParams
    };
    url = API_URL+url;
    let response:any={}
    try{
      response = await axios({
          method,
          url,
          ...(method !== "GET" && { data }),
          params,
          headers,
          responseType: "json",
        }); 
    }catch(error:any){
      if(error.status===409){
        Cookies.remove('token')
        Message.warning("token已过期,即将退出！")
        setTimeout(()=>{
          location.reload();
        },2000)
       
      }
      return error.response
    }
      return response;
  }
  createDatasets(data:any) {
    return this.sendRequest(
      routes.createDatasets.method,
      routes.createDatasets.url(),
      data
    );
  }
  datasets() {
    return this.sendRequest(
      routes.datasets.method,
      routes.datasets.url(),
    );
  }
  documents(params:any) {
      return this.sendRequest(
        routes.documents.method,
        routes.documents.url(params.dataset_id),
        params
      );
  }
  downloadDocument(params:any){
    return this.sendRequest(
      routes.downloadDocument.method,                                    //dataset_id:any,document_id:any
      routes.downloadDocument.url(params.dataset_id,params.document_id),
    );
  }
  uploadDocument(data:any){
    return this.sendRequest(
      routes.uploadDocument.method,      
      routes.uploadDocument.url(data.dataset_id),
      data
    );
  }
}

export default TwoDifyClient

